<?php

class SparesController extends Controller {

    public $errors = array();
    public $config = array(
        'ooospares' => 'http://ooospares.ru/search.html?c=search&pgsize=50&searche=1&idc=0&stype=1&searchword=',
        'gsmbaza' => 'http://www.gsmbaza.ru/search.php?x=9&y=16&stype=name&search=',
        'green_spark' => 'green-spark.ru/catalog',
        'mobile_parts' => 'http://mobile-parts.ru/search/?x=0&y=0&str=',
        'tfl_shop' => 'http://tfl-shop.ru/search/?query=',
        'sensor_ekran' => 'http://sensor-ekran.ru/site_search?search_term=',
        'tablets_spb' => 'http://tablets.spb.ru/search/?query=',
//        'vodoley_nsk' => 'http://водолей-нск.рф/search/?keyword=',
        'multimediacity' => 'http://www.multimediacity.ru/search/?how=r&SHOWALL_3=1&q=',
//        'boottec' => 'http://boottec.ru/search/?q=',
        'itsell' => 'http://itsell.ru/search/?searchstring=',
        'foneks' => 'http://foneks.ru/index.php?route=product/search&category_id=0&keyword=',
        'Tdelectronics' => 'http://3delectronics.ru/index.php?route=product/search&limit=100&filter_name=',
    );
    public $regions = array('Москва', 'Санкт-Петербург', 'Нижний Новгород', 'Екатеринбург', 'Новосибирск', 'Казань');

    public function actionYaAPI() {
        if (isset($_GET['mid'])) {
            $mid = $_GET['mid'];
            $url = 'https://api.partner.market.yandex.ru/v2/models/' . $mid . '.json?oauth_token=b3af57742c0e4c258828dfcd64cf0d82&oauth_client_id=dc78d5de910f45c5b43205034bb3d492&oauth_login=raybtru&regionId=213';
            echo Yii::app()->curl->get($url);
        }
        if (isset($_GET['title'])) {
            $title = $_GET['title'];
            $url = 'https://api.partner.market.yandex.ru/v2/models.json?oauth_token=b3af57742c0e4c258828dfcd64cf0d82&oauth_client_id=dc78d5de910f45c5b43205034bb3d492&oauth_login=raybtru&regionId=213&query=' . $title;            
            echo Yii::app()->curl->get($url);            
        }
        Yii::app()->end();
    }

    function multiRequest($data, $options = array()) {

        // array of curl handles
        $curly = array();
        // data to be returned
        $result = array();

        // multi handle
        $mh = curl_multi_init();

        // loop through $data and create curl handles
        // then add them to the multi-handle
        foreach ($data as $id => $d) {

            $curly[$id] = curl_init();

            $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
            curl_setopt($curly[$id], CURLOPT_URL, $url);
            curl_setopt($curly[$id], CURLOPT_HEADER, 0);
            curl_setopt($curly[$id], CURLOPT_FOLLOWLOCATION, 0);
            curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);

            // post?
            if (is_array($d)) {
                if (!empty($d['post'])) {
                    curl_setopt($curly[$id], CURLOPT_POST, 1);
                    curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
                }
            }

            // extra options?
            if (!empty($options)) {
                curl_setopt_array($curly[$id], $options);
            }

            curl_multi_add_handle($mh, $curly[$id]);
        }

        // execute the handles
        $running = null;
        do {
            curl_multi_exec($mh, $running);
        } while ($running > 0);


        // get content and remove handles
        foreach ($curly as $id => $c) {
            $result[$id] = curl_multi_getcontent($c);
            curl_multi_remove_handle($mh, $c);
        }

        // all done
        curl_multi_close($mh);

        return $result;
    }

    function multiple_threads_request($nodes) {
        $mh = curl_multi_init();
        $curl_array = array();
        foreach ($nodes as $i => $url) {
            $curl_array[$i] = curl_init($url);
            curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true);
            curl_multi_add_handle($mh, $curl_array[$i]);
        }
        $running = NULL;
        do {
            usleep(10000);
            curl_multi_exec($mh, $running);
        } while ($running > 0);

        $res = array();
        foreach ($nodes as $i => $url) {
            $res[$url] = curl_multi_getcontent($curl_array[$i]);
        }

        foreach ($nodes as $i => $url) {
            curl_multi_remove_handle($mh, $curl_array[$i]);
        }
        curl_multi_close($mh);
        return $res;
    }

    public $products = array();

    public function actionCall($m, $search) {
        header('Content-Type: application/json');
        echo json_encode($this->$m($search));
        Yii::app()->end();
    }

    public function actionIndex() {
        set_time_limit(0);
        ini_set("display_errors", 0);
        error_reporting(0);
        $path = Yii::app()->basePath . '/../uploads/';
        $file = $path . 'test.txt';
        file_put_contents($file, json_encode($_REQUEST));
        $search = !empty($_GET['search']) ? $_GET['brand'] . ' ' . $_GET['model'] . $_GET['search'] : $_GET['brand'] . ' ' . $_GET['model'];
        $region = empty($_GET['region']) ? 0 : array_search($_GET['region'], $this->regions);
        $sql = "SELECT
                    sp.spare_region AS city ,
                    sup.sp_title AS shop_title ,
                    REPLACE( sup.sp_site ,'http://' ,'' ) AS shop_link ,
                    sp.spare_title AS product_title ,
                    sp.spare_avail AS product_count ,
                    sp.spare_opt_price - sp.spare_opt_price *(
                        CASE
                            WHEN sp.spare_sale_opt IS NULL
                            THEN 0
                            ELSE sp.spare_sale_opt
                        END
                    ) / 100 AS price_opt ,
                    sp.spare_rozn_price - sp.spare_rozn_price *(
                        CASE
                            WHEN sp.spare_sale_rozn IS NULL
                            THEN 0
                            ELSE sp.spare_sale_rozn
                        END
                    ) / 100 AS price_rozn ,
                    sp.spare_load_time
                FROM
                    (
                        SELECT
                            spp.*
                        FROM
                            mp_spares spp ,
                            (
                                SELECT
                                    spare_title ,
                                    MAX(spare_load_time) AS spare_lt
                                FROM
                                    mp_spares
                                WHERE ";
        $sql .= empty($_GET['region']) ? '' : 'spare_region = \'' . $region . '\' AND ';

        $brand = trim(strip_tags($_GET['brand']));
        $model = trim(strip_tags($_GET['model']));
        $search = trim(strip_tags($_GET['search']));

        $brand = explode(' ', $brand);
        foreach ((array) $brand as $b) {
            $brandSQL[] = 'UPPER( spare_title ) LIKE UPPER( \'%' . $b . '%\' )';
        }
        $brandSQL = implode(' OR ', $brandSQL);

        $model = explode(' ', $model);
        foreach ((array) $model as $m) {
            $modelSQL[] = '(UPPER( spare_title ) LIKE UPPER( \'%' . $m . '%\' ))';
        }
        $modelSQL = implode(' OR ', $modelSQL);

        $sql .= '(' . $brandSQL . ')';
        $sql .= 'AND ';
        $sql .= '(' . $modelSQL . ')';
        $sql .=!empty($_GET['search']) ? 'AND UPPER (spare_title) LIKE UPPER (\'%' . $search . '%\')' : '';
        $sql .= "                                   
                                GROUP BY
                                    spare_title
                            ) T
                        WHERE
                            spp.spare_title = T . spare_title
                            AND spp.spare_load_time = T . spare_lt
                    ) sp INNER JOIN mp_suppliers sup
                        ON sp.supp_id = sup.sp_id";
//echo $sql;exit;
        $models = Yii::app()->dbClaris->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        foreach ($models as $key => $model) {
            $models[$key]['city'] = $this->regions[$models[$key]['city']];
        }
        header('Content-Type: application/json');
        echo json_encode($models);
        Yii::app()->end();

        $path = Yii::app()->basePath . '/../uploads/';
        $file = $path . 'test.txt';
        file_put_contents($file, json_encode($_REQUEST));
        $search = '';

        if (!empty($_REQUEST['brand'])) {
            $search .= $_REQUEST['brand'];
        }
        if (!empty($_REQUEST['model'])) {
            $search .= ' ' . $_REQUEST['model'];
        }
        if (!empty($_REQUEST['search'])) {
            $search .= ' ' . $_REQUEST['search'];
        }
//        echo $search;exit;
        //$search = !empty($_GET['search']) ? $_GET['search'] : $_GET['brand'] . ' ' . $_GET['model'];
        $methods = array('Tdelectronics', 'gsmbaza', 'foneks', 'itsell', 'multimediacity', 'tablets_spb', 'sensor_ekran', 'tfl_shop', 'green_spark', 'mobile_parts');
        foreach ($methods as $m) {
            $data[] = 'http://' . Yii::app()->request->serverName . '/spares/call?m=' . $m . '&search=' . urlencode($search);
        }

        $r = array();
        $array = array();
        $res = $this->multiple_threads_request($data);
//        echo '<pre>';
//        print_r($res);
//        exit;

        foreach ($res as $json) {
            $j = json_decode($json, true);
            if (!empty($j))
                $r = $r + $j;
        }

        if (isset($_GET['region']) && !empty($_GET['region'])) {
            foreach ($r as $a) {
                if ($a['city'] == $_GET['region'])
                    $array[] = $a;
            }
        }else {
            $array = $r;
        }
        header('Content-Type: application/json');
        echo json_encode($array);
        Yii::app()->end();
    }

    public function Tdelectronics($search) {
        $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
        Yii::import('ext.phpQuery');
        $doc = phpQuery::newDocument(str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $out));
        foreach ($doc['.product-list div'] as $key => $tr) {
            $name = pq($tr)->find('div.name a')->text();
            if (!empty($name))
                $products[] = [
                    'city' => 'Москва',
                    'shop_title' => '3delectronics',
                    'shop_link' => '3delectronics.ru',
                    'product_title' => $name,
                    'product_count' => 1,
                    'product_price' => (int) pq($tr)->find('.price')->text()
                ];
        }
        return $products;
    }

    public function foneks($search) {
        $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
        Yii::import('ext.phpQuery');
        $doc = phpQuery::newDocument(str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $out));
        foreach ($doc['.list tr td'] as $key => $tr) {
            $name = pq($tr)->find('a')->text();
            if (!empty($name))
                $products[] = [
                    'city' => 'Москва',
                    'shop_title' => 'foneks',
                    'shop_link' => 'foneks.ru',
                    'product_title' => $name,
                    'product_count' => 1,
                    'product_price' => (int) pq($tr)->find('span[style="color: #900; font-weight: bold;"]')->text()
                ];
        }
        return $products;
    }

    public function itsell($search) {
        $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
        Yii::import('ext.phpQuery');
        $doc = phpQuery::newDocument($out);
        foreach ($doc['.catalog tr td'] as $key => $tr) {
            $name = pq($tr)->find('.pr_brief h3 a')->text();
            if (!empty($name))
                $products[] = [
                    'city' => 'Москва',
                    'shop_title' => 'itsell',
                    'shop_link' => 'itsell.ru',
                    'product_title' => $name,
                    'product_count' => 1,
                    'product_price' => preg_replace("/[^0-9]/", '', pq($tr)->find('.pr_brief form .catalog-incart button')->text())
                ];
        }
        return $products;
    }

//    public function boottec($search) {
//        $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
//        echo $out;exit;
//        Yii::import('ext.phpQuery');
//        $doc = phpQuery::newDocument($out);
//        foreach ($doc['.search-page table tr'] as $key => $tr) {
//            $name = pq($tr)->find('td:nth-child(2) a')->text();
//            if (!empty($name))
//                $products[$region][] = array(
//                    'number' => $key,
//                    'name' => $name,
//                    'price' => preg_replace("/[^0-9]/", '', pq($tr)->find('.block_tovar .tovar .hid_it .price_tov .gray_price')->text()),
//                    'quantity' => 1
//                );
//        }
//
//        return $products;
//    }

    public function multimediacity($search) {
        $regions = array('moskva' => 131, 'spb' => 128, 'nnov' => 133, 'ekb' => 147, 'novosbirsk' => 135, 'kazan' => 97);
        foreach ($regions as $region => $cookie) {
            Yii::app()->curl->setOptions(array(CURLOPT_COOKIE => 'region=' . $cookie . ';'));
            $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
            Yii::import('ext.phpQuery');
            $doc = phpQuery::newDocument($out);
            foreach ($doc['.right_column .catalog_2 ul li'] as $key => $tr) {
                $name = pq($tr)->find('.block_tovar .tovar .name_tov')->text();
                if (!empty($name))
                    $products[] = [
                        'city' => 'Москва',
                        'shop_title' => 'tablets.spb',
                        'shop_link' => 'tablets.spb.ru',
                        'product_title' => $name,
                        'product_count' => 1,
                        'product_price' => preg_replace("/[^0-9]/", '', pq($tr)->find('.block_tovar .tovar .hid_it .price_tov .gray_price')->text())
                    ];
            }
        }
        return $products;
    }

//    public function vodoley_nsk($search) {
//        $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
//        Yii::import('ext.phpQuery');
//        $doc = phpQuery::newDocument($out);
//        foreach ($doc['.product-list li'] as $key => $tr) {
//            $name = pq($tr)->find('.product-block .text .name a span')->text();
//            if (!empty($name))
//                $products['moskva'][] = array(
//                    'number' => $key,
//                    'name' => $name,
//                    'price' => preg_replace("/[^0-9]/", '', pq($tr)->find('.product-block .offers .price')->text()),
//                    'quantity' => pq($tr)->find('.product-block .offers .available')->text()
//                );
//        }
//        return $products;
//    }

    public function tablets_spb($search) {
        $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
        Yii::import('ext.phpQuery');
        $doc = phpQuery::newDocument($out);
        foreach ($doc['.product-list li'] as $key => $tr) {
            $name = pq($tr)->find('.product-block .text .name a span')->text();
            if (!empty($name))
                $products[] = [
                    'city' => 'Санкт-Петербург',
                    'shop_title' => 'tablets.spb',
                    'shop_link' => 'tablets.spb.ru',
                    'product_title' => $name,
                    'product_count' => pq($tr)->find('.product-block .offers .available')->text(),
                    'product_price' => preg_replace("/[^0-9]/", '', pq($tr)->find('.product-block .offers .price')->text())
                ];
        }
        return $products;
    }

    public function sensor_ekran($search) {
        $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
        Yii::import('ext.phpQuery');
        $doc = phpQuery::newDocument($out);
        foreach ($doc['.b-product-line'] as $key => $tr) {
            $name = pq($tr)->find('.b-product-line__details-panel .b-product-line__product-name a.b-product-line__product-name-link span')->text();
            if (!empty($name))
                $products[] = [
                    'city' => 'Москва',
                    'shop_title' => 'sensor_ekran',
                    'shop_link' => 'sensor-ekran.ru',
                    'product_title' => $name,
                    'product_count' => pq($tr)->find('.b-product-line__details-panel .b-product-line__data .b-product-line__state')->text(),
                    'product_price' => preg_replace("/[^0-9]/", '', pq($tr)->find('.b-product-line__details-panel .b-product-line__price-bar .b-product-line__price')->text()),
                ];
        }
        return $products;
    }

    public function tfl_shop($search) {
        $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
        Yii::import('ext.phpQuery');
        $doc = phpQuery::newDocument($out);
        foreach ($doc['.product-list li'] as $key => $tr) {
            $name = pq($tr)->find('.product-block .text .name a span')->text();
            if (!empty($name))
                $products[] = [
                    'city' => 'Москва',
                    'shop_title' => 'tfl_shop',
                    'shop_link' => 'tfl-shop.ru',
                    'product_title' => $name,
                    'product_count' => pq($tr)->find('.product-block .offers .available')->text(),
                    'product_price' => preg_replace("/[^0-9]/", '', pq($tr)->find('.product-block .offers .price')->text()),
                ];
        }
        return $products;
    }

    public function mobile_parts($search) {
        $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
        Yii::import('ext.phpQuery');
        $doc = phpQuery::newDocument($out);
//        echo $out;
        foreach ($doc['.item'] as $tr) {
            $name = pq($tr)->find('.body .name strong a')->text();
            if (!empty($name))
                $products[] = [
                    'city' => 'Москва',
                    'shop_title' => 'mobile-parts',
                    'shop_link' => 'mobile-parts.ru',
                    'product_title' => $name,
                    'product_count' => preg_replace("/[^0-9]/", '', pq($tr)->find('.body .this-stock .blue')->text()),
                    'product_price' => preg_replace("/[^0-9]/", '', pq($tr)->find('.price .current')->text()),
                ];
        }
        return $products;
    }

    public function ooospares($search) {
        $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
        Yii::import('ext.phpQuery');
        $doc = phpQuery::newDocument($out);
//        echo $out;
        foreach ($doc['tr[align="center"]'] as $tr) {
            $name = pq($tr)->find('.goods:nth-child(2) b')->text();
            preg_match_all('#c51407;">(.*) руб.#', pq($tr)->find('script')->text(), $matches);
            if (!empty($name))
                $products[] = [
                    'city' => 'Москва',
                    'shop_title' => 'ooospares',
                    'shop_link' => 'ooospares.ru',
                    'product_title' => $name,
                    'product_count' => preg_replace("/[^0-9]/", '', pq($tr)->find('.goods:nth-child(3)')->text()),
                    'product_price' => (int) $matches[1][0],
                ];
        }
        return $products;
    }

    public function gsmbaza($search) {
        //$products['site'] = __FUNCTION__;
        $out = Yii::app()->curl->get($this->config[__FUNCTION__] . $search);
        Yii::import('ext.phpQuery');
        $doc = phpQuery::newDocument($out);
        foreach ($doc['.smallparams2'] as $tr) {
            preg_match('#Оптовая цена: (?P<digit>\d+)#', pq($tr)->find('.price')->text(), $matches);
            $products[] = [
                'city' => 'Москва',
                'shop_title' => 'gsmbaza',
                'shop_link' => 'gsmbaza.ru',
                'product_title' => pq($tr)->find('.cl b a')->text(),
                'product_count' => pq($tr)->find('div:nth-child(7) img')->attr('title'),
                'product_price' => isset($matches['digit']) ? $matches['digit'] : 0
            ];
        }
        return $products;
    }

    public function green_spark($search) {
        //$products['site'] = __FUNCTION__;
        $regions = array('moskva' => 'Москва', 'spb' => 'Санкт-Петербург', 'nnov' => 'Нижний Новгород', 'kazan' => 'Казань');
        foreach ($regions as $l => $region) {
//            echo 'http://' . $region . '.' . $this->config[__FUNCTION__] . '<br >';
            $out = Yii::app()->curl->post('http://' . $l . '.' . $this->config[__FUNCTION__], array(
                'search' => $search, 'action' => 'get_list',
                'filter[amount]' => false,
                'filter[original]' => true,
                'filter[search]' => $search,
                'filter[sort]' => false,
                'id_parent' => 0));
            Yii::import('ext.phpQuery');
//            print_r($out);
            $doc = phpQuery::newDocument($out);
            foreach ($doc['.catalog_item'] as $key => $tr) {
                preg_match('#Оптовая цена: (?P<digit>\d+)#', pq($tr)->find('.price')->text(), $matches);
                $products[] = [
                    'city' => $region,
                    'shop_title' => 'green_spark',
                    'shop_link' => 'green-spark.ru',
                    'product_title' => pq($tr)->find('.top a')->text(),
                    'product_count' => pq($tr)->find('.w20p .state')->text(),
                    'product_price' => (int) pq($tr)->find('.fs14 .item_price a span')->text(),
                ];
            }
        }
        return $products;
    }

}
